package angry.courses.beans;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import angry.courses.entities.RelationEntity;

@Stateless
public class RelationDAOBean implements RelationDAO {
	@PersistenceContext
	private EntityManager em;
	
	public void create(int courseID, int studentID) {
		RelationEntity relation = new RelationEntity(courseID, studentID);
		em.persist(relation);
	}

	public List<Integer> getStudentIdsForCourse(int cid) {
		List<Integer> sids = null;
		try {
			Query query = em.createNamedQuery("retrieveSidsForCid");
			query.setParameter("cid", cid);
			sids = (List<Integer>) query.getResultList();
		} catch(Exception e) {
			sids = new ArrayList<Integer>();
		}
		return sids;
	}
	
	public List<Integer> getCourseIdsForStudent(int sid) {
		List<Integer> cids = null;
		try {
			Query query = em.createNamedQuery("retrieveCidsForSid");
			query.setParameter("sid", sid);
			cids = (List<Integer>) query.getResultList();
		} catch(Exception e) {
			cids = new ArrayList<Integer>();
		}
		return cids;
	}
	
	public List<RelationEntity> getRelationsForStudent(int sid) {
		List<RelationEntity> relations = null;
		try {
			Query query = em.createNamedQuery("retrieveRelationsForSid");
			query.setParameter("sid", sid);
			relations = (List<RelationEntity>) query.getResultList();
		} catch(Exception e) {
			relations = new ArrayList<RelationEntity>();
		}
		return relations;
	}
	
	public List<RelationEntity> getRelationsForCourse(int cid) {
		List<RelationEntity> relations = null;
		try {
			Query query = em.createNamedQuery("retrieveRelationsForCid");
			query.setParameter("cid", cid);
			relations = (List<RelationEntity>) query.getResultList();
		} catch(Exception e) {
			relations = new ArrayList<RelationEntity>();
		}
		return relations;
	}
	
	public void remove(RelationEntity relation) {
		RelationEntity existing = em.find(RelationEntity.class, relation.getRelationID());
		em.remove(existing);
//		em.remove(relation);
	}
}
